package com.iceberg;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;

public class AlgorithmVisualizer {

    // TODO: 创建自己的数据
    private int DELAY = 40;
    private QuickSort data;        // 数据
    private AlgorithmFrame frame;    // 视图

    public AlgorithmVisualizer(int sceneWidth, int sceneHeight, int N){

        // 初始化数据
        // TODO: 初始化数据
        this.data = new QuickSort(N, sceneHeight);
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgorithmFrame("Welcome", sceneWidth, sceneHeight);
            // TODO: 根据情况决定是否加入键盘鼠标事件监听器
            frame.addKeyListener(new AlgoKeyListener());
            frame.addMouseListener(new AlgoMouseListener());
            new Thread(() -> {
                run();
            }).start();
        });
    }

    // 动画逻辑
    private void run(){
        setData(-1, -1, -1, -1, -1);
        quickSort(0, data.N()-1);
        setData(-1, -1, -1, -1, -1);
    }

    private void quickSort(int l, int r){
        if (l > r){
            return;
        }
        if (l == r){
            setData(l, r, l,-1, -1);
            return;
        }
        setData(l, r, -1, -1, -1);
        int p = partition(l, r);
        quickSort(l, p-1);
        quickSort(p+1, r);
    }

    private int partition(int l, int r){
        int v = data.get(l);
        setData(l, r, -1, l, -1);

        int j = l;// arr[l+1...j] < v ; v < arr[j+1...v]
        for (int i = l + 1; i <= r; i++){
            setData(l, r, -1, l, i);
            if (data.get(i) < v){
                j++;
                data.swap(j, i);
            }
        }
        data.swap(l, j);
        setData(l, r, j, -1, -1);
        return j;
    }

    private void setData(int l, int r, int fixedPivot, int curPivot, int curElement){
        data.l = l;
        data.r = r;
        if (fixedPivot != -1)
            data.fixedPivot[fixedPivot] = true;
        data.curElement = curElement;
        frame.render(data);
        AlgorithmVisHelper.pause(DELAY);
    }

    // TODO: 根据情况决定是否实现键盘鼠标等交互事件监听器类
    private class AlgoKeyListener extends KeyAdapter{ }
    private class AlgoMouseListener extends MouseAdapter{ }

    public static void main(String[] args) {

        int sceneWidth = 800;
        int sceneHeight = 800;

        // TODO: 根据需要设置其他参数，初始化visualizer
        AlgorithmVisualizer visualizer = new AlgorithmVisualizer(sceneWidth, sceneHeight, 100);
    }
}
